"""
    Author:
    Date: 2018-11-01

    GM管理类
"""

import time

from django.conf import settings

import env
from utils import db
from utils import sms
from utils.log import Log


def send_sms_code(mobile, code):
    """ 给指定的手机发送验证码 """
    if not settings.DEBUG:
        # # 一分钟之内只能发送一次验证码
        # send_time = db.redis_get(f'sms:time:{mobile}')
        # if (send_time is not None) and (int(time.time()) - int(send_time)) < 60:
        #     Log.info(f'Cannot duplicate send sms code: mobile={mobile}')
        #     return False
        key = f'sms:time:{mobile}'
        db.redis_set(key, int(time.time()))
        db.redis_expire(key, 10 * 60)

        success = sms.send_sms_code(mobile, code, settings.YP_SMS_API_KEY)
        if not success:
            Log.error(f'Send sms code failed: mobile={mobile}')
            return False

    Log.info(f'Send sms code ok: mobile={mobile}, code={code}, type={type(code)}')
    key = f'sms:{mobile}'
    db.redis_set(key, code)
    db.redis_expire(key, 10 * 60)
    return True


def is_valid_sms_code(mobile, code):
    """ 检测验证码是否合法 """
    Log.info(f'setting={settings.DEBUG}, code={code}')
    if env.DEBUG and code == '1313':
        return True

    # 测试账号处理
    if mobile in env.TEST_MOBILES and code == '1313':
        return True

    cache = db.redis_get(f'sms:{mobile}')
    Log.info(f'Cached code is {cache}, code={code}')
    return cache == code


def send_redpack_sms_message(mobile, rmb, wid):
    """ 给指定的手机发送红包通知消息 """
    text = f"【APP】亲爱的用户，您申请的奖励红包{rmb}元已经发放(单号{wid})，请注意查收！"
    if not env.DEBUG:
        success = sms.send_sms_message(mobile, text, settings.YP_SMS_API_KEY)
        if not success:
            Log.error(f'Send sms message failed: mobile={mobile}, text={text}')
            return False

    Log.info(f'Send sms message ok: mobile={mobile}, text={text}')
    return True


if __name__ == '__main__':
    print('ok')
